const express = require('express')
const { queryDB, queryDBPromise } = require('../db/db.js')

const userRouter = express.Router()

/**
 * 注册
 */
userRouter.post('/register', (req, res) => {
	const username = req.body.username
	const password = req.body.password
	const age = req.body.age
	const sex = req.body.sex

	// 检查用户名是否已经注册
	const sql1 = `SELECT count(*) AS num FROM users WHERE username = '${username}'`
	
	queryDBPromise(sql1).then(data => {
		if (data[0].num > 0) {
			res.send({
				code: -1,
				message: '用户已经注册',
			})
		} else {
			// 保存到数据库
			const sql = `INSERT INTO users (username,password,age,sex)VALUES('${username}','${password}',${age},'${sex}')`
			queryDBPromise(sql).then(data => {
				res.send({
					code: 1,
					message: '注册用户成功!',
				})
			})
		}
	})
})

/**
 * 登录
 */
userRouter.post('/login', (req, res) => {
	const username = req.body.username //用户名
	const password = req.body.password //密码

	// 登录本质: 根据用户名和密码，查询数据库用户表，有无该记录
	const sql = `SELECT id,username,password,url,age FROM users WHERE username = '${username}' AND password = '${password}'`
	queryDBPromise(sql).then(data => {
		console.log('data >> :', data)

		if (data.length > 0) {
			res.send({
				code: 1,
				message: '登录成功',
				user:data[0]
				
			})
		} else {
			res.send({
				code: -1,
				message: '用户名或密码出错!',
			})
		}
	})
})

module.exports = { userRouter }
